//
//  DecorateViewController.m
//  PerfectWorld
//
//  Created by dllo on 16/8/27.
//  Copyright © 2016年 LST. All rights reserved.
//

#import "DecorateViewController.h"
#import "DecorateHeaderTableViewCell.h"
#import "HeaderFourBtnView.h"
#import "RightSearchViewController.h"
#import "AFNetworking.h"
#import "RootModel.h"
#import "Projects.h"
#import "UserImage.h"
#import "User.h"
#import "Banners.h"
#import "CycleModel.h"
#import "WYScrollView.h"
#import "DecorateSonViewController.h"
#import "NetworkHandler.h"
#import "LoginLeftViewController.h"
#import "FreeDesignWebViewController.h"
#import "MJRefresh.h"
#import "JSDropDownMenu.h"
#import "LoginSonViewController.h"
@interface DecorateViewController ()<UITableViewDataSource, UITableViewDelegate, WYScrollViewNetDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)RootModel *rootModel;
@property (nonatomic, strong)CycleModel *cycleModel;
@property (nonatomic, strong)NSMutableArray<Projects *> *arr;
@property (nonatomic, strong)UIButton *btn;
@property (nonatomic, assign)NSInteger page;
@end
@implementation DecorateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    image.image = [UIImage imageNamed:@"logo"];
    self.navigationItem.titleView = image;
    self.arr = [NSMutableArray array];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    // 左
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(5 , 0, 30 , 30 );
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"头像"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(clickNavLeftBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    // 右
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(clickNavRightBtn:)];
    [self creatTableView];
    [self creatCycleData];
    [self creatButton];
    // 下拉刷新, 上拉加载
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 0;
        [self handData];
    }];
    [_tableView.mj_header beginRefreshing];
    _tableView.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
        [self creatMJRefreshFoot];
    }];
}
// 悬浮按钮
- (void)creatButton {
    self.btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btn setTitle:@"免费设计" forState:UIControlStateNormal];
    _btn.frame = CGRectMake(self.view.bounds.size.width - 90, self.view.bounds.size.height / 2 + 100, 50, 50);
    _btn.layer.cornerRadius = 25;
    _btn.backgroundColor = [UIColor colorWithRed:0.44 green:0.81 blue:0.98 alpha:1.00];
    _btn.titleLabel.font = [UIFont systemFontOfSize:10];
    [_btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.view addSubview:_btn];
}
// 免费设计按钮关联
- (void)clickBtn:(UIButton *)sender {
    FreeDesignWebViewController *freeWebVC = [[FreeDesignWebViewController alloc] init];
    [self.navigationController pushViewController:freeWebVC animated:YES];
}
// 网络请求
- (void)handData {
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/project/list?style=0&type=0&area=0&cost=0&user=(null)&start=%ld&count=10", (long)_page];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (_page == 0) {
            _arr = nil;
        }
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
        self.rootModel = [RootModel modelWithDic:dic];
        _arr = [NSMutableArray arrayWithArray:_rootModel.projects];
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
}
// 轮播图网络请求
- (void)creatCycleData {
    NSString *urlStr = @"http://api.guju.com.cn/v2/project/banner?src=appBannerOfProject";
    dispatch_queue_t concurrent = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(concurrent, ^{
        [NetworkHandler getDataByUrlString:urlStr BodyString:nil WithDataBlock:^(id result) {
            NSDictionary *dic = result;
            self.cycleModel = [CycleModel modelWithDic:dic];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self creatCycleView];
            });
        }];
    });
}
- (void)creatMJRefreshFoot {
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/project/list?style=0&type=0&area=0&cost=0&user=(null)&start=%ld&count=10", (long)(_page += 10)];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
        self.rootModel = [RootModel modelWithDic:dic];
        [_arr addObjectsFromArray:_rootModel.projects];
        [_tableView reloadData];
        [_tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
}
// 创建轮播图
- (void)creatCycleView {
    NSMutableArray *sourceArray = [NSMutableArray array];
    for (Banners *banners in _cycleModel.banners) {
        [sourceArray addObject:banners.imgUrl];
    }
    WYScrollView *cycleView = [[WYScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 2.5) WithNetImages:sourceArray];
    cycleView.netDelagate = self;
    [cycleView setAutoScrollDelay:2];
    _tableView.tableHeaderView = cycleView;
}
// tableView
- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[DecorateHeaderTableViewCell class] forCellReuseIdentifier:@"cell"];
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.view.bounds.size.height / 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DecorateHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.projectModel = _arr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DecorateSonViewController *sonVC = [[DecorateSonViewController alloc] init];
    
    sonVC.urlId = _arr[indexPath.row].Son_id.description;
    sonVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sonVC animated:YES];
}
// 导航左按钮关联
- (void)clickNavLeftBtn:(UIBarButtonItem *)leftBtn {
    NSUserDefaults *user = [[NSUserDefaults standardUserDefaults]objectForKey:@"dic"];
    NSDictionary *dic = [user objectForKey:@"user"];
    NSString *str = [dic objectForKey:@"userName"];
    if (str.length > 0) {
        LoginSonViewController *textName = [[LoginSonViewController alloc] init];
        [self.navigationController pushViewController:textName animated:YES];
    } else {
    LoginLeftViewController *loginVC = [[LoginLeftViewController alloc] init];
    loginVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:loginVC animated:YES];
    }
}
// 导航右按钮关联
// 400-670-1855
// 021-26107491
- (void)clickNavRightBtn:(UIBarButtonItem *)rightBtn {
    RightSearchViewController *searchVC = [[RightSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
    [_window resignKeyWindow];
    _window = nil;
}
// 轮播图点击
-(void)didSelectedNetImageAtIndex:(NSInteger)index {
    DecorateSonViewController *sonVC = [[DecorateSonViewController alloc] init];
    sonVC.urlId = _cycleModel.banners[index].httpUrl;
    sonVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:sonVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
